package com.zs.client;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class DownLoadClient {
	public static void main(String[] args) {
		DownLoadClient client = new DownLoadClient();
		client.run();

	}

	public void run() {
		for (int i = 0; i < 5; i++) {
			new DownLoadThread(i).start();
		}
	}

	class DownLoadThread extends Thread {

		Socket socket = null;
		OutputStream requestServer = null;
		BufferedOutputStream outBuffer = null;
		InputStream in = null;
		int id;

		public DownLoadThread(int id) {
			this.id = id;
		}

		@Override
		public void run() {
			try {
				socket = new Socket();
				socket.connect(new InetSocketAddress("192.168.1.101", 8090));
				requestServer = socket.getOutputStream();
				in = socket.getInputStream();
				requestServer.write(("i'am Thread--" + id).getBytes());

				System.out.println("recevice ...response");
				outBuffer = new BufferedOutputStream(new FileOutputStream(new File("/home/movie", id + "rmvb")));
				byte[] b = new byte[1024 * 1024];
				int len = 0;
				while ((len = in.read(b)) != -1) {
					outBuffer.write(b, 0, len);
				}

			} catch (Exception e) {
				e.printStackTrace();

			} finally {
				try {
					if (socket != null) {
						socket.close();
					}
					if (requestServer != null) {
						requestServer.close();
					}
					if (in != null) {
						in.close();
					}
					if (outBuffer == null) {
						outBuffer.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}

		}

	}

}
